<template>
  <div class="abnormal-order-manage">
    <h2>异常处理</h2>

    <!-- 搜索筛选区域 -->
    <div class="search-container" style="margin: 0 20px 20px; padding: 15px; border: 1px solid #e6e6e6; border-radius: 8px; background: #f9f9f9;">
      <el-input
          v-model="searchOrderNo"
          placeholder="请输入订单号"
          style="width: 200px; margin-right: 10px;"
          clearable
      />
      <el-select
          v-model="searchAbnormalType"
          placeholder="选择异常类型"
          style="width: 180px; margin-right: 10px;"
          clearable
      >
        <el-option label="商品做错" value="商品做错" />
        <el-option label="规格错误（甜度/冰量）" value="规格错误" />
        <el-option label="小料遗漏/错误" value="小料错误" />
        <el-option label="订单漏做" value="订单漏做" />
        <el-option label="支付异常" value="支付异常" />
        <el-option label="其他异常" value="其他异常" />
      </el-select>
      <el-select
          v-model="searchHandleStatus"
          placeholder="选择处理状态"
          style="width: 150px; margin-right: 10px;"
          clearable
      >
        <el-option label="待处理" value="待处理" />
<!--        <el-option label="处理中" value="处理中" />-->
        <el-option label="已处理" value="已处理" />
      </el-select>
      <el-date-picker
          v-model="searchDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 300px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset" style="margin-left: 10px;">重置</el-button>
    </div>

    <!-- 异常订单列表 -->
    <div style="margin: 0 20px;">
      <el-table
          :data="abnormalOrderList"
          border
          stripe
          style="width: 100%;"
          :empty-text="listLoading ? '加载中...' : '暂无异常订单'"
      >
<!--        <el-table-column label="记录ID" prop="id" width="100" align="center" />-->
        <el-table-column label="订单号" prop="orderNo" align="center"/>
        <el-table-column label="订单日期" prop="orderDate" width="180" align="center">
          <template #default="scope">{{ formatDate(scope.row.orderDate) }}</template>
        </el-table-column>
        <el-table-column label="异常类型" prop="abnormalType" width="150" align="center"/>
        <el-table-column label="提交人" prop="createBy" width="120" align="center" />
        <el-table-column label="提交时间" prop="createTime" width="200" align="center">
          <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="处理状态" prop="handleStatus" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.handleStatus === '待处理' ? 'warning' : scope.row.handleStatus === '处理中' ? 'info' : 'success'">
              {{ scope.row.handleStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row)">查看详情</el-button>
            <el-button
                type="success"
                size="small"
                @click="handleOrder(scope.row)"
                style="margin-left: 8px;"
                :disabled="scope.row.handleStatus === '已处理'"
            >
              {{ scope.row.handleStatus === '待处理' ? '处理订单' : '处理完成' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 15px; text-align: right;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        />
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog title="异常订单详情" v-model="isDetailDialogOpen" width="600px">
      <div class="detail-content">
        <div class="detail-item">
          <span class="detail-label">记录ID：</span>
          <span class="detail-value">{{ currentDetail.id || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">订单号：</span>
          <span class="detail-value">{{ currentDetail.orderNo || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">订单日期：</span>
          <span class="detail-value">{{ currentDetail.orderDate ? formatDate(currentDetail.orderDate) : '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">异常类型：</span>
          <span class="detail-value">{{ currentDetail.abnormalType || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">异常描述：</span>
          <span class="detail-value">{{ currentDetail.abnormalDesc || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">处理建议：</span>
          <span class="detail-value">{{ currentDetail.suggestion || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">提交人：</span>
          <span class="detail-value">{{ currentDetail.createBy || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">提交时间：</span>
          <span class="detail-value">{{ currentDetail.createTime ? formatDate(currentDetail.createTime) : '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">处理状态：</span>
          <span class="detail-value">
            <el-tag :type="currentDetail.handleStatus === '待处理' ? 'warning' : currentDetail.handleStatus === '处理中' ? 'info' : 'success'">
              {{ currentDetail.handleStatus || '-' }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item" v-if="currentDetail.handleBy">
          <span class="detail-label">处理人：</span>
          <span class="detail-value">{{ currentDetail.handleBy || '-' }}</span>
        </div>
        <div class="detail-item" v-if="currentDetail.handleRemark">
          <span class="detail-label">处理备注：</span>
          <span class="detail-value">{{ currentDetail.handleRemark || '-' }}</span>
        </div>
        <div class="detail-item" v-if="currentDetail.handleTime">
          <span class="detail-label">处理时间：</span>
          <span class="detail-value">{{ currentDetail.handleTime ? formatDate(currentDetail.handleTime) : '-' }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="isDetailDialogOpen = false">关闭</el-button>
      </template>
    </el-dialog> <!-- 修复：补全详情弹窗的结束标签 -->

    <!-- 处理订单弹窗 -->
    <el-dialog title="处理异常订单" v-model="isHandleDialogOpen" width="500px">
      <el-form :model="handleForm" :rules="handleRules" ref="handleFormRef" label-width="100px">
        <el-form-item label="订单号" disabled>
          <el-input v-model="handleForm.orderNo" />
        </el-form-item>
        <el-form-item label="当前状态" disabled>
          <el-input v-model="handleForm.currentStatus" />
        </el-form-item>
        <el-form-item label="处理状态" prop="handleStatus">
          <el-select v-model="handleForm.handleStatus" style="width: 100%;">
            <el-option label="处理中" value="处理中" />
            <el-option label="已处理" value="已处理" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="handleRemark">
          <el-input
              v-model="handleForm.handleRemark"
              type="textarea"
              :rows="4"
              placeholder="请输入处理结果（如：已在后台重新更改库存，下次请注意）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isHandleDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="submitHandleResult">提交处理结果</el-button>
      </template>
    </el-dialog> <!-- 处理弹窗的结束标签已正确闭合 -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/axios/http'

// 搜索筛选条件
const searchOrderNo = ref('')
const searchAbnormalType = ref('')
const searchHandleStatus = ref('')
const searchDateRange = ref([]) // 日期范围：[开始日期, 结束日期]

// 列表数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const abnormalOrderList = ref([])
const listLoading = ref(false)

// 弹窗控制
const isDetailDialogOpen = ref(false)
const isHandleDialogOpen = ref(false)
const currentDetail = ref({})

// 处理表单
const handleFormRef = ref(null)
const handleForm = ref({
  id: '', // 异常订单记录ID
  orderNo: '', // 订单号
  currentStatus: '', // 当前状态
  handleStatus: '', // 处理后状态
  handleRemark: '', // 处理备注
  handleBy: '管理员' // 处理人
})

// 处理表单校验规则
const handleRules = ref({
  handleStatus: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  handleRemark: [{ required: true, message: '请输入处理备注', trigger: 'blur' }, { min: 5, message: '备注至少5个字符', trigger: 'blur' }]
})

// 页面加载时获取异常订单列表
onMounted(() => {
  getAbnormalOrderList()
})

// 获取异常订单列表
const getAbnormalOrderList = async () => {
  try {
    listLoading.value = true
    // 构造查询参数
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      orderNo: searchOrderNo.value,
      abnormalType: searchAbnormalType.value,
      handleStatus: searchHandleStatus.value,
      startDate: searchDateRange.value[0] ? new Date(searchDateRange.value[0]).toISOString() : '',
      endDate: searchDateRange.value[1] ? new Date(searchDateRange.value[1]).toISOString() : ''
    }

    const res = await http.post('/glsb/admin/get_abnormal_order_list', params)
    if (res.data.result === 'success') {
      abnormalOrderList.value = res.data.data.list || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error('获取异常订单列表失败：' + res.data.msg)
    }
  } catch (err) {
    ElMessage.error('网络错误，请重试')
    console.error(err)
  } finally {
    listLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pageNum.value = 1
  getAbnormalOrderList()
}

// 重置
const handleReset = () => {
  searchOrderNo.value = ''
  searchAbnormalType.value = ''
  searchHandleStatus.value = ''
  searchDateRange.value = []
  pageNum.value = 1
  getAbnormalOrderList()
}

// 分页改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getAbnormalOrderList()
}
const handleCurrentChange = (val) => {
  pageNum.value = val
  getAbnormalOrderList()
}

// 查看详情
const viewDetail = (row) => {
  currentDetail.value = { ...row }
  isDetailDialogOpen.value = true
}

// 处理订单
const handleOrder = (row) => {
  handleForm.value = {
    id: row.id,
    orderNo: row.orderNo,
    currentStatus: row.handleStatus,
    handleStatus: row.handleStatus === '待处理' ? '处理中' : row.handleStatus,
    handleRemark: row.handleRemark || '',
    handleBy: '管理员'
  }
  isHandleDialogOpen.value = true
}

// 提交处理结果
const submitHandleResult = async () => {
  try {
    await handleFormRef.value.validate()

    const submitData = {
      id: handleForm.value.id,
      handleStatus: handleForm.value.handleStatus,
      handleRemark: handleForm.value.handleRemark,
      handleBy: handleForm.value.handleBy,
      handleTime: new Date().toISOString() // 处理时间
    }

    const res = await http.post('/glsb/admin/handle_abnormal_order', submitData)
    if (res.data.result === 'success') {
      ElMessage.success('处理结果提交成功！')
      isHandleDialogOpen.value = false
      getAbnormalOrderList() // 刷新列表
    } else {
      ElMessage.error('提交失败：' + res.data.msg)
    }
  } catch (err) {
    ElMessage.error('表单校验失败，请检查必填项')
    console.error(err)
  }
}

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.abnormal-order-manage {
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}
.search-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
.detail-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px 0;
}
.detail-item {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}
.detail-label {
  font-weight: 500;
  width: 100px;
  flex-shrink: 0;
  color: #666;
}
.detail-value {
  flex: 1;
  color: #333;
  line-height: 1.5;
}
</style>